package com.tecode.gmail.user.util;

import com.tecode.gmail.util.DateUtil;
import com.tecode.gmail.util.SMSConf;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2019-01-03
 * @Description:
 * 短信相关的工具类
 */
@Component
public class SMSUtil {




	public  Map<String,Object> sendSMS(String phone){
		Map<String,Object> map = new HashedMap();

		//验证码
		String code = getVerificationCode();

		//获得时间戳
		String timestamp = DateUtil.dateToString(new Date(),"yyyyMMddHHmmss");

		//获得签名
		String sig = DigestUtils.md5DigestAsHex((SMSConf.ACCOUNT_SID + SMSConf.AUTH_TOKEN +timestamp).getBytes());

		String outputStr="accountSid=" + SMSConf.ACCOUNT_SID+"&smsContent=" +SMSConf.SMS_CONTENT +"\n" +
				"    &to=" +phone +"&timestamp=" + timestamp +"&sig=" + sig+"&respDataType=" +SMSConf.RESP_DATA_TYPE;

		outputStr = outputStr.replaceAll("V_CODE",code).replaceAll("TIME","10");

		JSONObject jsonObject = JSONObject.fromObject("{\"respCode\":\"00000\",\"respDesc\":\"请求成功。\",\"failCount\":\"0\",\"failList\":[],\"smsId\":\"09f1439c129e415aba724c429a6c92a3\"}");
		//JSONObject jsonObject = SendUrl.httpRequest(SMSConf.SMS_URL, SMSConf.METHOD, outputStr);
		System.out.println("验证码为：" +code);
		try {
			if(jsonObject.get("respCode").equals("00000")){
				map.put("result",true);
				map.put("msg","短信发送成功");
				map.put("code",code);
			}

		}catch (Exception e){
			map.put("result",false);
			map.put("msg","短信发送失败");
		}


		return map;
	}

	/**
	 * @Author Gabriel
	 * @Description //TODO
	 * @Date 2019/1/3
	 * @Param
	 * @Return
	 * 返回验证码
	 */
	public String getVerificationCode(){
		return  new DecimalFormat("000000").format(Math.random() * 1000000);
	}

}